<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" th:replace="~{layout/base :: layout(~{::title}, ~{::content}, ~{::css}, ~{::js})}">
<head>
    <title>编辑笔记 - 笔记管理系统</title>
    <th:block th:fragment="css">
        <link href="https://cdn.jsdelivr.net/npm/quill@1.3.7/dist/quill.snow.css" rel="stylesheet">
        <style>
            .form-container {
                background: white;
                border-radius: 10px;
                padding: 30px;
                box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            }
            .editor-container {
                height: 400px;
                margin-bottom: 20px;
            }
            .tag-input-container {
                position: relative;
            }
            .tag-suggestions {
                position: absolute;
                top: 100%;
                left: 0;
                right: 0;
                background: white;
                border: 1px solid #ddd;
                border-top: none;
                border-radius: 0 0 5px 5px;
                max-height: 200px;
                overflow-y: auto;
                z-index: 1000;
                display: none;
            }
            .tag-suggestion {
                padding: 10px;
                cursor: pointer;
                border-bottom: 1px solid #eee;
            }
            .tag-suggestion:hover {
                background-color: #f8f9fa;
            }
            .tag-suggestion:last-child {
                border-bottom: none;
            }
            .selected-tags {
                margin-top: 10px;
            }
            .tag-item {
                display: inline-block;
                background: #007bff;
                color: white;
                padding: 5px 10px;
                margin: 2px;
                border-radius: 15px;
                font-size: 0.875rem;
            }
            .tag-item .remove-tag {
                margin-left: 5px;
                cursor: pointer;
                font-weight: bold;
            }
            .form-actions {
                border-top: 1px solid #eee;
                padding-top: 20px;
                margin-top: 30px;
                text-align: right;
            }
            .btn-group .btn {
                margin-left: 10px;
            }
        </style>
    </th:block>
</head>
<body>
    <div th:fragment="content">
        <!-- 页面标题 -->
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h2>
                <i class="fas fa-edit me-2"></i><span id="pageTitle">编辑笔记</span>
            </h2>
            <a href="/note" class="btn btn-outline-secondary">
                <i class="fas fa-arrow-left me-2"></i>返回列表
            </a>
        </div>

        <!-- 编辑表单 -->
        <div class="form-container">
            <form id="noteForm">
                <input type="hidden" id="noteId" name="id">

                <div class="row">
                    <div class="col-md-8">
                        <div class="mb-3">
                            <label for="title" class="form-label">标题 <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="title" name="title" required>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="mb-3">
                            <label for="categoryId" class="form-label">分类</label>
                            <select class="form-select" id="categoryId" name="categoryId">
                                <option value="">请选择分类</option>
                                <!-- 分类选项将通过AJAX加载 -->
                            </select>
                        </div>
                    </div>
                </div>

                <div class="mb-3">
                    <label for="summary" class="form-label">摘要</label>
                    <textarea class="form-control" id="summary" name="summary" rows="3" placeholder="请输入笔记摘要"></textarea>
                </div>

                <div class="mb-3">
                    <label for="tagInput" class="form-label">标签</label>
                    <div class="tag-input-container">
                        <input type="text" class="form-control" id="tagInput" placeholder="输入标签名称，按回车添加">
                        <div class="tag-suggestions" id="tagSuggestions"></div>
                    </div>
                    <div class="selected-tags" id="selectedTags"></div>
                    <input type="hidden" id="tagIds" name="tagIds">
                </div>

                <div class="mb-3">
                    <label class="form-label">内容 <span class="text-danger">*</span></label>
                    <div id="editor" class="editor-container"></div>
                    <textarea id="content" name="content" style="display: none;"></textarea>
                </div>

                <div class="row">
                    <div class="col-md-4">
                        <div class="mb-3">
                            <label for="status" class="form-label">状态</label>
                            <select class="form-select" id="status" name="status">
                                <option value="0">草稿</option>
                                <option value="1">发布</option>
                            </select>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="mb-3">
                            <div class="form-check mt-4">
                                <input class="form-check-input" type="checkbox" id="isTop" name="isTop" value="1">
                                <label class="form-check-label" for="isTop">
                                    置顶显示
                                </label>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="mb-3">
                            <div class="form-check mt-4">
                                <input class="form-check-input" type="checkbox" id="isPublic" name="isPublic" value="1">
                                <label class="form-check-label" for="isPublic">
                                    公开显示
                                </label>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="form-actions">
                    <div class="btn-group">
                        <button type="button" class="btn btn-outline-secondary" onclick="history.back()">取消</button>
                        <button type="button" class="btn btn-outline-primary" onclick="saveDraft()">保存草稿</button>
                        <button type="submit" class="btn btn-primary">保存并发布</button>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <th:block th:fragment="js">
        <script src="https://cdn.jsdelivr.net/npm/quill@1.3.7/dist/quill.min.js"></script>
        <script>
            let quill;
            let selectedTags = [];
            let allTags = [];
            let noteId = null;

            $(document).ready(function() {
                initEditor();
                loadCategories();
                loadTags();

                // 获取URL中的笔记ID
                let pathParts = window.location.pathname.split('/');
                if (pathParts[pathParts.length - 1] !== 'add') {
                    noteId = pathParts[pathParts.length - 1];
                    loadNote(noteId);
                } else {
                    $('#pageTitle').text('新建笔记');
                }

                // 表单提交
                $('#noteForm').on('submit', function(e) {
                    e.preventDefault();
                    saveNote(1); // 保存并发布
                });

                // 标签输入处理
                $('#tagInput').on('input', function() {
                    let query = $(this).val().trim();
                    if (query.length > 0) {
                        showTagSuggestions(query);
                    } else {
                        hideTagSuggestions();
                    }
                });

                $('#tagInput').on('keydown', function(e) {
                    if (e.key === 'Enter') {
                        e.preventDefault();
                        let tagName = $(this).val().trim();
                        if (tagName) {
                            addTag(tagName);
                            $(this).val('');
                            hideTagSuggestions();
                        }
                    }
                });

                // 点击其他地方隐藏标签建议
                $(document).on('click', function(e) {
                    if (!$(e.target).closest('.tag-input-container').length) {
                        hideTagSuggestions();
                    }
                });
            });

            // 初始化编辑器
            function initEditor() {
                quill = new Quill('#editor', {
                    theme: 'snow',
                    modules: {
                        toolbar: [
                            [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
                            ['bold', 'italic', 'underline', 'strike'],
                            [{ 'color': [] }, { 'background': [] }],
                            [{ 'list': 'ordered'}, { 'list': 'bullet' }],
                            [{ 'indent': '-1'}, { 'indent': '+1' }],
                            [{ 'align': [] }],
                            ['blockquote', 'code-block'],
                            ['link', 'image'],
                            ['clean']
                        ]
                    }
                });
            }

            // 加载分类列表
            function loadCategories() {
                $.get('/note/category/listAll', function(data) {
                    if (data.code === 200) {
                        let options = '<option value="">请选择分类</option>';
                        data.data.forEach(function(category) {
                            options += `<option value="${category.id}">${category.categoryName}</option>`;
                        });
                        $('#categoryId').html(options);
                    }
                });
            }

            // 加载标签列表
            function loadTags() {
                $.get('/note/tag/listAll', function(data) {
                    if (data.code === 200) {
                        allTags = data.data;
                    }
                });
            }

            // 加载笔记详情
            function loadNote(id) {
                $.get(`/note/detail/${id}`, function(data) {
                    if (data.code === 200) {
                        let note = data.data;
                        $('#noteId').val(note.id);
                        $('#title').val(note.title);
                        $('#summary').val(note.summary);
                        $('#categoryId').val(note.categoryId);
                        $('#status').val(note.status);
                        $('#isTop').prop('checked', note.isTop === 1);
                        $('#isPublic').prop('checked', note.isPublic === 1);

                        // 设置编辑器内容
                        if (note.content) {
                            quill.root.innerHTML = note.content;
                        }

                        // 设置标签
                        if (note.tags && note.tags.length > 0) {
                            selectedTags = note.tags.map(tag => ({
                                id: tag.id,
                                tagName: tag.tagName
                            }));
                            updateSelectedTags();
                        }
                    } else {
                        showError('加载笔记失败：' + data.msg);
                    }
                });
            }

            // 显示标签建议
            function showTagSuggestions(query) {
                let suggestions = allTags.filter(tag =>
                    tag.tagName.toLowerCase().includes(query.toLowerCase()) &&
                    !selectedTags.some(selected => selected.id === tag.id)
                );

                if (suggestions.length > 0) {
                    let html = '';
                    suggestions.forEach(function(tag) {
                        html += `<div class="tag-suggestion" onclick="selectTag(${tag.id}, '${tag.tagName}')">${tag.tagName}</div>`;
                    });
                    $('#tagSuggestions').html(html).show();
                } else {
                    hideTagSuggestions();
                }
            }

            // 隐藏标签建议
            function hideTagSuggestions() {
                $('#tagSuggestions').hide();
            }

            // 选择标签
            function selectTag(id, name) {
                addTag(name, id);
                $('#tagInput').val('');
                hideTagSuggestions();
            }

            // 添加标签
            function addTag(tagName, tagId = null) {
                // 检查是否已存在
                if (selectedTags.some(tag => tag.tagName === tagName)) {
                    return;
                }

                selectedTags.push({
                    id: tagId,
                    tagName: tagName
                });

                updateSelectedTags();
            }

            // 移除标签
            function removeTag(index) {
                selectedTags.splice(index, 1);
                updateSelectedTags();
            }

            // 更新选中的标签显示
            function updateSelectedTags() {
                let html = '';
                selectedTags.forEach(function(tag, index) {
                    html += `<span class="tag-item">${tag.tagName}<span class="remove-tag" onclick="removeTag(${index})">×</span></span>`;
                });
                $('#selectedTags').html(html);

                // 更新隐藏字段
                let tagIds = selectedTags.filter(tag => tag.id).map(tag => tag.id).join(',');
                let tagNames = selectedTags.filter(tag => !tag.id).map(tag => tag.tagName).join(',');
                $('#tagIds').val(tagIds + (tagIds && tagNames ? ',' : '') + tagNames);
            }

            // 保存草稿
            function saveDraft() {
                saveNote(0);
            }

            // 保存笔记
            function saveNote(status) {
                // 验证必填字段
                if (!$('#title').val().trim()) {
                    showError('请输入标题');
                    return;
                }

                if (!quill.getText().trim()) {
                    showError('请输入内容');
                    return;
                }

                // 设置内容
                $('#content').val(quill.root.innerHTML);
                $('#status').val(status);

                // 构建表单数据
                let formData = {
                    id: $('#noteId').val(),
                    title: $('#title').val(),
                    summary: $('#summary').val(),
                    content: $('#content').val(),
                    categoryId: $('#categoryId').val() || null,
                    status: $('#status').val(),
                    isTop: $('#isTop').is(':checked') ? 1 : 0,
                    isPublic: $('#isPublic').is(':checked') ? 1 : 0,
                    tagIds: selectedTags.filter(tag => tag.id).map(tag => tag.id),
                    tagNames: selectedTags.filter(tag => !tag.id).map(tag => tag.tagName).join(',')
                };

                let url = noteId ? '/note/edit' : '/note/add';

                $.post(url, formData, function(data) {
                    if (data.code === 200) {
                        showSuccess(status === 1 ? '发布成功' : '保存成功');
                        setTimeout(function() {
                            window.location.href = '/note';
                        }, 1000);
                    } else {
                        showError('保存失败：' + data.msg);
                    }
                });
            }

            // 显示成功消息
            function showSuccess(message) {
                alert(message); // 简单实现，可以替换为更好的提示组件
            }

            // 显示错误消息
            function showError(message) {
                alert(message); // 简单实现，可以替换为更好的提示组件
            }
        </script>
    </th:block>
</body>
</html>
